<template>
  <div class="login-page">
    <Header />
    <div class="login-container">
      <div class="login-form">
        <!-- 添加切换登录/注册的标签 -->
        <div class="form-toggle">
          <button
              :class="{ active: formType === 'login' }"
              @click="switchForm('login')"
          >
            {{ $t('login.login') }}
          </button>
          <button
              :class="{ active: formType === 'register' }"
              @click="switchForm('register')"
          >
            {{ $t('login.register') }}
          </button>
        </div>

        <h2 v-if="formType === 'login'">{{ $t('login.title') }}</h2>
        <h2 v-else>{{ $t('login.registerTitle') }}</h2>

        <!-- 登录表单 -->
        <form v-if="formType === 'login'" @submit.prevent="handleLogin">
          <div class="form-group">
            <label for="account">{{ $t('login.accountLabel') }}:</label>
            <input
                type="text"
                id="account"
                v-model="loginForm.account"
                :placeholder="$t('login.accountPlaceholder')"
                required
            />
            <div class="error-message" v-if="loginErrors.account">
              {{ loginErrors.account }}
            </div>
          </div>

          <div class="form-group" v-if="loginMethod === 'password'">
            <label for="password">{{ $t('login.passwordLabel') }}:</label>
            <input
                type="password"
                id="password"
                v-model="loginForm.password"
                :placeholder="$t('login.passwordPlaceholder')"
                required
            />
            <div class="error-message" v-if="loginErrors.password">
              {{ loginErrors.password }}
            </div>
          </div>

          <div class="form-group" v-if="loginMethod === 'code'">
            <label for="code">{{ $t('login.codeLabel') }}:</label>
            <div class="code-input">
              <input
                  type="text"
                  id="code"
                  v-model="loginForm.code"
                  :placeholder="$t('login.codePlaceholder')"
                  required
              />
              <button
                  type="button"
                  @click="sendCode"
                  :disabled="codeSending || countdownActive"
                  class="send-code-btn"
              >
                {{ codeButtonText }}
              </button>
            </div>
            <div class="error-message" v-if="loginErrors.code">
              {{ loginErrors.code }}
            </div>
          </div>

          <div class="form-group">
            <button type="submit" class="login-button" :disabled="loggingIn">
              {{ loggingIn ? $t('login.loggingIn') : $t('login.login') }}
            </button>
          </div>

          <div class="login-method-toggle">
            <div class="toggle-buttons">
              <div
                  class="toggle-button"
                  :class="{ active: loginMethod === 'password' }"
                  @click="switchLoginMethod('password')"
              >
                <div class="icon">🔒</div>
                <span>{{ $t('login.passwordLogin') }}</span>
              </div>
              <div
                  class="toggle-button"
                  :class="{ active: loginMethod === 'code' }"
                  @click="switchLoginMethod('code')"
              >
                <div class="icon">📱</div>
                <span>{{ $t('login.codeLogin') }}</span>
              </div>
            </div>
          </div>
        </form>

        <!-- 注册表单 -->
        <form v-else @submit.prevent="handleRegister">
          <div class="form-group">
            <label for="register-account">{{ $t('login.accountLabel') }}:</label>
            <input
                type="text"
                id="register-account"
                v-model="registerForm.account"
                :placeholder="$t('login.accountPlaceholder')"
                required
            />
            <div class="error-message" v-if="registerErrors.account">
              {{ registerErrors.account }}
            </div>
          </div>

          <div class="form-group" v-if="registerMethod === 'password'">
            <label for="register-password">{{ $t('login.passwordLabel') }}:</label>
            <input
                type="password"
                id="register-password"
                v-model="registerForm.password"
                :placeholder="$t('login.passwordPlaceholder')"
                required
            />
            <div class="error-message" v-if="registerErrors.password">
              {{ registerErrors.password }}
            </div>
          </div>

          <div class="form-group" v-if="registerMethod === 'password'">
            <label for="confirm-password">{{ $t('login.confirmPasswordLabel') }}:</label>
            <input
                type="password"
                id="confirm-password"
                v-model="registerForm.confirmPassword"
                :placeholder="$t('login.confirmPasswordPlaceholder')"
                required
            />
            <div class="error-message" v-if="registerErrors.confirmPassword">
              {{ registerErrors.confirmPassword }}
            </div>
          </div>

          <div class="form-group" v-if="registerMethod === 'code'">
            <label for="register-code">{{ $t('login.codeLabel') }}:</label>
            <div class="code-input">
              <input
                  type="text"
                  id="register-code"
                  v-model="registerForm.code"
                  :placeholder="$t('login.codePlaceholder')"
                  required
              />
              <button
                  type="button"
                  @click="sendRegisterCode"
                  :disabled="codeSending || countdownActive"
                  class="send-code-btn"
              >
                {{ codeButtonText }}
              </button>
            </div>
            <div class="error-message" v-if="registerErrors.code">
              {{ registerErrors.code }}
            </div>
          </div>

          <div class="form-group">
            <button type="submit" class="login-button" :disabled="registering">
              {{ registering ? $t('login.registering') : $t('login.register') }}
            </button>
          </div>

          <!-- 注册方式切换 -->
          <div class="login-method-toggle">
            <div class="toggle-buttons">
              <div
                  class="toggle-button"
                  :class="{ active: registerMethod === 'password' }"
                  @click="switchRegisterMethod('password')"
              >
                <div class="icon">🔒</div>
                <span>{{ $t('login.passwordRegister') }}</span>
              </div>
              <div
                  class="toggle-button"
                  :class="{ active: registerMethod === 'code' }"
                  @click="switchRegisterMethod('code')"
              >
                <div class="icon">📱</div>
                <span>{{ $t('login.codeRegister') }}</span>
              </div>
            </div>
          </div>
        </form>

        <div class="error-message" v-if="errorMessage && !hasFieldErrors">
          {{ errorMessage }}
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import Header from '../components/Header.vue';
import api from '../services/api';

export default {
  name: 'LoginPage',
  components: {
    Header
  },
  data() {
    return {
      formType: 'login', // 'login' or 'register'
      loginForm: {
        account: '',
        password: '',
        code: ''
      },
      registerForm: {
        account: '',
        password: '',
        confirmPassword: '',
        code: ''
      },
      loginMethod: 'password', // password or code
      registerMethod: 'password', // password or code
      loggingIn: false,
      registering: false,
      errorMessage: '',
      loginErrors: {},
      registerErrors: {},
      codeSending: false,
      countdown: 60,
      countdownActive: false,
      countdownTimer: null
    };
  },
  computed: {
    // 计算属性：验证账号是否有效
    isAccountValid() {
      const account = this.formType === 'login'
          ? this.loginForm.account
          : this.registerForm.account;
      return account && account.trim().length > 0;
    },
    codeButtonText() {
      if (this.countdownActive) {
        return this.$t('login.resendCode', { time: this.countdown });
      }
      return this.$t('login.sendCode');
    },
    hasFieldErrors() {
      const errors = this.formType === 'login' ? this.loginErrors : this.registerErrors;
      return Object.keys(errors).length > 0;
    }
  },
  methods: {
    switchForm(type) {
      this.formType = type;
      this.errorMessage = '';
      this.loginErrors = {};
      this.registerErrors = {};
      this.stopCountdown();
    },

    validateLoginForm() {
      const errors = {};

      if (!this.loginForm.account.trim()) {
        errors.account = this.$t('login.accountRequired');
      }

      if (this.loginMethod === 'password') {
        if (!this.loginForm.password) {
          errors.password = this.$t('login.passwordRequired');
        }
      } else if (this.loginMethod === 'code') {
        if (!this.loginForm.code) {
          errors.code = this.$t('login.codeRequired');
        }
      }

      this.loginErrors = errors;
      return Object.keys(errors).length === 0;
    },

    validateRegisterForm() {
      const errors = {};

      if (!this.registerForm.account.trim()) {
        errors.account = this.$t('login.accountRequired');
      }

      if (this.registerMethod === 'password') {
        if (!this.registerForm.password) {
          errors.password = this.$t('login.passwordRequired');
        } else if (this.registerForm.password.length < 6) {
          errors.password = this.$t('login.passwordTooShort');
        }

        if (!this.registerForm.confirmPassword) {
          errors.confirmPassword = this.$t('login.confirmPasswordRequired');
        } else if (this.registerForm.password !== this.registerForm.confirmPassword) {
          errors.confirmPassword = this.$t('login.passwordMismatch');
        }
      } else if (this.registerMethod === 'code') {
        if (!this.registerForm.code) {
          errors.code = this.$t('login.codeRequired');
        }
      }

      this.registerErrors = errors;
      return Object.keys(errors).length === 0;
    },
    async handleLogin() {
      this.errorMessage = '';

      if (!this.validateLoginForm()) {
        return;
      }

      this.loggingIn = true;

      try {
        const requestData = { ...this.loginForm };

        if (this.loginMethod === 'password') {
          requestData.loginType = 'password';
        } else {
          requestData.loginType = 'code';
        }

        const response = await api.post('/auth/login', requestData);

        if (response.success) {
          // Login success: save token and redirect to home page
          localStorage.setItem('token', response.data); // Save token

          // Fetch user information
          const userInfoResponse = await api.get('/auth/get-user-info');
          if (userInfoResponse.success) {
            // Save user info to localStorage
            const user = userInfoResponse.data;
            localStorage.setItem('user', JSON.stringify(user)); // Store user info in localStorage

            this.$router.push('/'); // Redirect to home page
          }else {
            this.errorMessage = this.$t('login.getUserInfoErr');
          }


        } else {
          this.errorMessage = response.message;
        }
      } catch (error) {
        this.errorMessage = this.$t('login.loginFailed') + (error.message || this.$t('login.unknownError'));
      } finally {
        this.loggingIn = false;
      }
    }    ,

    async handleRegister() {
      this.errorMessage = '';

      if (!this.validateRegisterForm()) {
        return;
      }

      this.registering = true;

      try {
        const requestData = { ...this.registerForm };

        if (this.registerMethod === 'password') {
          requestData.registerType = 'password';
          delete requestData.code;
        } else {
          requestData.registerType = 'code';
        }

        const response = await api.post('/auth/register', requestData);

        if (response.success) {
          // Register success: automatically log the user in
          this.loginForm.account = this.registerForm.account;
          this.loginForm.password = this.registerForm.password;
          await this.handleLogin();
        } else {
          this.errorMessage = response.message;
        }
      } catch (error) {
        this.errorMessage = this.$t('login.registerFailed') + (error.message || this.$t('login.unknownError'));
      } finally {
        this.registering = false;
      }
    },

    async sendCode() {
      if (!this.isAccountValid) {
        this.loginErrors = {
          ...this.loginErrors,
          account: this.$t('login.enterAccountFirst')
        };
        return;
      }

      this.codeSending = true;
      this.errorMessage = '';
      // 删除 account 错误
      const { account, ...rest } = this.loginErrors;
      this.loginErrors = rest;

      try {
        // 调用发送验证码的接口
        const response = await api.post('/auth/send-code', {
          account: this.loginForm.account
        });

        if (response.success) {
          this.startCountdown();
        } else {
          this.loginErrors = {
            ...this.loginErrors,
            account: response.message || this.$t('login.sendCodeFailed')
          };
        }
      } catch (error) {
        this.loginErrors = {
          ...this.loginErrors,
          account: this.$t('login.sendCodeFailed') + (error.message || this.$t('login.unknownError'))
        };
      } finally {
        this.codeSending = false;
      }
    },

    async sendRegisterCode() {
      if (!this.isAccountValid) {
        this.registerErrors = {
          ...this.registerErrors,
          account: this.$t('login.enterAccountFirst')
        };
        return;
      }

      this.codeSending = true;
      this.errorMessage = '';
      // 删除 account 错误
      const { account, ...rest } = this.registerErrors;
      this.registerErrors = rest;

      try {
        // 调用发送注册验证码的接口
        const response = await api.post('/auth/send-code', {
          account: this.registerForm.account
        });

        if (response.success) {
          this.startCountdown();
        } else {
          this.registerErrors = {
            ...this.registerErrors,
            account: response.message || this.$t('login.sendCodeFailed')
          };
        }
      } catch (error) {
        this.registerErrors = {
          ...this.registerErrors,
          account: this.$t('login.sendCodeFailed') + (error.message || this.$t('login.unknownError'))
        };
      } finally {
        this.codeSending = false;
      }
    },

    startCountdown() {
      this.countdownActive = true;
      const updateCountdown = () => {
        this.countdown--;
        if (this.countdown <= 0) {
          this.stopCountdown();
        }
      };
      this.countdownTimer = setInterval(updateCountdown, 1000);
    },

    stopCountdown() {
      if (this.countdownTimer) {
        clearInterval(this.countdownTimer);
        this.countdownTimer = null;
      }
      this.countdownActive = false;
      this.countdown = 60;
    },

    // 添加切换登录方式的方法
    switchLoginMethod(method) {
      this.loginMethod = method;
      // 切换时清除错误信息
      this.errorMessage = '';
      this.loginErrors = {};
      this.loginForm.code='';
      this.loginForm.password='';

      // 停止倒计时
      this.stopCountdown();
    },

    // 添加切换注册方式的方法
    switchRegisterMethod(method) {
      this.registerMethod = method;
      // 切换时清除错误信息
      this.errorMessage = '';
      this.registerErrors = {};
      this.registerForm.code='';
      this.registerForm.password='';
      this.registerForm.confirmPassword='';
      // 停止倒计时
      this.stopCountdown();
    }
  },

  beforeUnmount() {
    // 组件销毁前清除定时器
    this.stopCountdown();
  }
};
</script>


<style scoped>
.login-page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: calc(100vh - 60px); /* 减去header的大致高度 */
}

.login-form {
  width: 100%;
  max-width: 400px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  position: relative;
}

.login-form h2 {
  text-align: center;
  margin-bottom: 24px;
  color: #333;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 6px;
  font-weight: bold;
  color: #555;
}

.form-group input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-sizing: border-box;
}

.form-group input:focus {
  border-color: #007bff;
  outline: none;
}

.code-input {
  display: flex;
  gap: 10px;
}

.code-input input {
  flex: 1;
}

.send-code-btn {
  padding: 10px 15px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  white-space: nowrap;
}

.send-code-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.login-button {
  width: 100%;
  padding: 12px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
}

.login-button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.error-message {
  color: #dc3545;
  font-size: 14px;
  margin-top: 5px;
}

/* 调整底部图标按钮切换样式 */
.login-method-toggle {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #eee;
}

.toggle-buttons {
  display: flex;
  justify-content: center;
  gap: 20px;
}

.toggle-button {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
  padding: 8px 12px; /* 缩小按钮尺寸 */
  border-radius: 6px;
  transition: all 0.3s ease;
  font-size: 12px; /* 缩小字体 */
}

.toggle-button:hover {
  background-color: #f0f0f0;
}

.toggle-button.active {
  color: #007bff;
  background-color: #e6f2ff;
}

.toggle-button .icon {
  font-size: 18px; /* 缩小图标 */
  margin-bottom: 3px;
}

.toggle-button span {
  font-size: 12px; /* 缩小文字 */
}

/* 添加表单切换样式 */
.form-toggle {
  display: flex;
  margin-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.form-toggle button {
  flex: 1;
  padding: 10px;
  background: none;
  border: none;
  cursor: pointer;
  font-weight: bold;
  color: #666;
}

.form-toggle button.active {
  color: #007bff;
  border-bottom: 2px solid #007bff;
}

.form-toggle button:focus {
  outline: none;
}
</style>

